package com.abel.bigwater.dataserver.model.hgd

import com.abel.bigwater.dataserver.model.PacketException
import io.netty.buffer.ByteBuf

/**
 * TEST DATA: @222:10000
 *
 * @author Abel
 */
class HgdaoTcpHeart : HgdaoBase {

    constructor() : super(HgdaoBase.TYPE_TCP)

    constructor(_type: String) : super(_type)

    @Throws(PacketException::class)
    fun parseBuffer(buf: ByteBuf): Boolean {
        return parseBuffer(buf, true)
    }

    @Throws(PacketException::class)
    override fun parseBuffer(buf: ByteBuf, ignoreChecksum: Boolean): Boolean {
        // should be @222:... if heart.
        if (buf.readableBytes() < 5) return false

        buf.duplicate().readBytes(5).apply {
            val str = toString(Charsets.ISO_8859_1)
            if (!str.startsWith("@222:")) {
                return false
            }
        }

        buf.duplicate().readBytes(Math.min(80, buf.readableBytes())).apply {
            val str = toString(Charsets.ISO_8859_1)
            val idx = str.indexOf("\r\n")

            return if (idx < 1) {
                buf.skipBytes(DEFAULT_LENGTH - 2)
                false
            } else {
                // consume bytes.
                buf.skipBytes(idx + 2)

                fmt = str.take(idx + 2)
                station = fmt?.substring(5)?.trim()
                true
            }
        }

        return true
    }

    override fun packBuf(buf: ByteBuf) {
        fmt = "@222:${station!!}\r\n"

        buf.writeBytes(fmt!!.toByteArray(Charsets.ISO_8859_1))
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    override fun toString(): String {
        return String.format("HgdaoTcpHeart [station=%s, buf=%s]", station, fmt)
    }

    companion object {
        const val MAX_LENGTH = 20

        const val DEFAULT_LENGTH = 5 + 5 + 2
    }

}
